<template>
  <div>
    <table>
      <tr>
        <th>
          <input type="checkbox" @click="checkAll" v-model="isAll" /> 全选
        </th>
        <th>商品</th>
        <th>单价（元）</th>
        <th>数量</th>
        <th>小计</th>
        <th>操作</th>
      </tr>
      <tr v-for="item in list" :key="item.id">
        <td><input type="checkbox" v-model="item.choosed" /></td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>
          <button @click="sub(item.num, item.id)">-</button
          ><input type="text" v-model="item.num" /><button @click="item.num++">
            +
          </button>
        </td>
        <td>{{ item.price * item.num }}</td>
        <td><button @click="deleteOne(item.id)">删除</button></td>
      </tr>
      <tr>
        <td><button @click="chooseDelete">删除选中商品</button></td>
        <td colspan="3">共{{ total }}件商品 已选中{{ checkTotal }}件商品</td>
        <td></td>
        <td colspan="2">合计金额：{{ totalPrice }} <button>结算</button></td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { id: 1, name: "苹果", price: "10", num: "1", choosed: true },
        { id: 2, name: "香蕉", price: "20", num: "1", choosed: false },
        { id: 3, name: "栗子", price: "15", num: "1", choosed: false },
        { id: 4, name: "李子", price: "30", num: "1", choosed: false }
      ]
    };
  },
  methods: {
    //全选
    checkAll(value) {
      this.list.forEach((v) => {
        v.choosed = value;
      });
    },
    // 减少
    sub(num, id) {
      if (num == 0) return;
      this.list = this.list.map((v) => {
        if (v.id == id) v.num--;
        return v;
      });
    },
    // 删除商品
    deleteOne(id) {
      this.list = this.list.filter((v) => id != v.id);
    },
    // 删除选中商品
    chooseDelete() {
      this.list = this.list.filter((v) => v.choosed !== true);
    }
  },
  computed: {
    //总数
    total() {
      return this.list.length;
    },
    //总价
    totalPrice() {
      let checkedList = this.list.filter((v) => v.choosed == true);
      return checkedList.reduce((pre, v) => pre + v.num * v.price, 0);
    },
    //已点
    checkTotal() {
      return this.list.reduce((pre, v) => pre + (v.choosed ? 1 : 0), 0);
    },
    //控制全选框
    isAll: {
      //全选框是否勾选
      get() {
        return this.checkTotal === this.total && this.total > 0;
      },
      //isAll被修改时set被调用,再调用全选按钮
      set(value) {
        this.checkAll(value);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
table {
  tr {
    text-align: center;
  }
}
</style>
